// import { ReactComponent as AssistantIcon } from '@/assets/svg/assistant.svg';
import { MessageType } from '@/constants/chat';
import { useSetModalState } from '@/hooks/common-hooks';
import { IReference, IReferenceChunk } from '@/interfaces/database/chat';
import classNames from 'classnames';
import { memo, useCallback,  useMemo, useState } from 'react';

import {
  useFetchDocumentInfosByIds,
  // useFetchDocumentThumbnailsByIds,
} from '@/hooks/document-hooks';
import { IRegenerateMessage, IRemoveMessageById } from '@/hooks/logic-hooks';
import { IMessage } from '@/pages/chat/interface';
import MarkdownContent from '@/pages/chat/markdown-content';
import { getExtension, isImage } from '@/utils/document-util';
import {  Button, Flex, List, Typography, Collapse, Badge } from 'antd';
import FileIcon from '../file-icon';
import IndentedTreeModal from '../indented-tree/modal';
import NewDocumentLink from '../new-document-link';
import { useTheme } from '../theme-provider';
import { AssistantGroupButton, UserGroupButton } from './group-button';
import styles from './index.less';
import { DownOutlined } from '@ant-design/icons';

const { Text } = Typography;

interface IProps extends Partial<IRemoveMessageById>, IRegenerateMessage {
  item: IMessage;
  reference: IReference;
  loading?: boolean;
  sendLoading?: boolean;
  visibleAvatar?: boolean;
  nickname?: string;
  avatar?: string;
  avatarDialog?: string | null;
  clickDocumentButton?: (documentId: string, chunk: IReferenceChunk) => void;
  index: number;
  showLikeButton?: boolean;
  showLoudspeaker?: boolean;
  isStreaming?: boolean;
}

const MessageItem = ({
  item,
  reference,
  loading = false,
  // avatar,
  // avatarDialog,
  sendLoading = false,
  clickDocumentButton,
  index,
  removeMessageById,
  regenerateMessage,
  showLikeButton = true,
  showLoudspeaker = true,
  isStreaming = false,
  // visibleAvatar = true,
}: IProps) => {
  const { theme } = useTheme();
  const isAssistant = item.role === MessageType.Assistant;
  const isUser = item.role === MessageType.User;
  const { data: documentList } = useFetchDocumentInfosByIds();
  // const { data: documentThumbnails, setDocumentIds: setIds } =
  //   useFetchDocumentThumbnailsByIds();
  const { visible, hideModal, showModal } = useSetModalState();
  const [clickedDocumentId, setClickedDocumentId] = useState('');

  const referenceDocumentList = useMemo(() => {
    return reference?.doc_aggs ?? [];
  }, [reference?.doc_aggs]);

  const handleUserDocumentClick = useCallback(
    (id: string) => () => {
      setClickedDocumentId(id);
      showModal();
    },
    [showModal],
  );

  const handleRegenerateMessage = useCallback(() => {
    regenerateMessage?.(item);
  }, [regenerateMessage, item]);

  // useEffect(() => {
  //   const ids = item?.doc_ids ?? [];
  //   if (ids.length) {
  //     setDocumentIds(ids);
  //     const documentIds = ids.filter((x) => !(x in documentThumbnails));
  //     if (documentIds.length) {
  //       setIds(documentIds);
  //     }
  //   }
  // }, [item.doc_ids, setDocumentIds, setIds, documentThumbnails]);

  // referenceDocumentList 按 doc_type 分组
  const grouped = useMemo(() => {
    const map = new Map();
    (referenceDocumentList as any[]).forEach(item => {
      if (!map.has(item.doc_type)) map.set(item.doc_type, []);
      map.get(item.doc_type).push(item);
    });
    return Array.from(map.entries());
  }, [referenceDocumentList]);
  // 折叠面板展开控制
  const [activeKeys, setActiveKeys] = useState<string[]>([]);

  return (
    <div
      className={classNames(styles.messageItem, {
        [styles.messageItemLeft]: item.role === MessageType.Assistant,
        [styles.messageItemRight]: item.role === MessageType.User,
      })}
    >
      <section
        className={classNames(styles.messageItemSection, {
          [styles.messageItemSectionLeft]: item.role === MessageType.Assistant,
          [styles.messageItemSectionRight]: item.role === MessageType.User,
        })}
      >
        <div
          className={classNames(styles.messageItemContent, {
            [styles.messageItemContentReverse]: item.role === MessageType.User,
          })}
        >
          <Flex vertical gap={8} flex={1}>
            <div
              className={
                isAssistant
                  ? theme === 'dark'
                    ? styles.messageTextDark
                    : styles.messageText
                  : styles.messageUserText
              }
            >
              <MarkdownContent
                loading={loading}
                content={item.content}
                reference={reference}
                clickDocumentButton={clickDocumentButton}
                isStreaming={isStreaming}
              ></MarkdownContent>
              {/* 分割线 */}
              {
                isAssistant && referenceDocumentList.length > 0 && (
                  <div className="h-[1px] bg-[#E3E3E3] my-2"></div>
                )
              }
              {isAssistant && referenceDocumentList.length > 0 && (
              <Collapse
                bordered={false}
                expandIcon={({ isActive }) => <DownOutlined rotate={isActive ? 180 : 0}/>}
                activeKey={activeKeys}
                onChange={keys => setActiveKeys(Array.isArray(keys) ? keys : [keys])}
                style={{ borderBottom: 'none', borderTop: 'none',backgroundColor: '#fff' }}
                expandIconPosition="end"
              >
                {grouped.map(([type, items]) => (
                  <Collapse.Panel
                    header={
                      <div
                        className="flex items-center px-0" // 宽度是img he badge 的宽度
                      >
                        <div className="bg-white border border-[#E3E3E3] rounded-[6px] py-[5px] px-[8px] md:py-2 md:px-3 h-6 md:h-9 flex items-center  font-medium text-[10px] md:text-sm ">
                        <img 
                          src={items[0]?.doc_type_icon}
                          alt="document"
                          className="h-2 md:h-3 mr-1"
                        />
                        {type}
                        </div>
                        
                        {/* // 红色小圆点 自适应，小屏幕下small 大屏幕下default */}
                        <Badge count={items.length} style={{ marginLeft: 8, background: '#F04438' }} size="small" /> 
                      </div>
                    }
                    key={type}
                  >
                    {(items as any[]).map(item => (
                      <div key={item.doc_id} style={{ marginBottom: 8 }}>
                        <Flex gap={'small'} align="center" className="text-[10px] md:text-sm">
                          <FileIcon
                            id={item.doc_id}
                            name={item.doc_name}
                            img={item.doc_image}
                            url={item.doc_url}
                          />
                          <NewDocumentLink
                            documentId={item.doc_id}
                            documentName={item.doc_name}
                            prefix="document"
                            link={item.doc_url}
                          >
                            {item.doc_name}
                          </NewDocumentLink>
                        </Flex>
                      </div>
                    ))}
                  </Collapse.Panel>
                ))}
              </Collapse>
            )}
            {isUser && documentList.length > 0 && (
              <List
                bordered
                dataSource={documentList}
                renderItem={(item) => {
                  // TODO:
                  // const fileThumbnail =
                  //   documentThumbnails[item.id] || documentThumbnails[item.id];
                  const fileExtension = getExtension(item.name);
                  console.log('那里item', item)
                  return (
                    <List.Item>
                      <Flex gap={'small'} align="center">
                        <FileIcon id={item.id} name={item.name}></FileIcon>

                        {isImage(fileExtension) ? (
                          <NewDocumentLink
                            documentId={item.id}
                            documentName={item.name}
                            prefix="document"
                          >
                            {item.name}
                          </NewDocumentLink>
                        ) : (
                          <Button
                            type={'text'}
                            onClick={handleUserDocumentClick(item.id)}
                          >
                            <Text
                              style={{ maxWidth: '40vw' }}
                              ellipsis={{ tooltip: item.name }}
                            >
                              {item.name}
                            </Text>
                          </Button>
                        )}
                      </Flex>
                    </List.Item>
                  );
                }}
              />
            )}
              
            </div>
           
            
             {/* 底部工具栏区域 */}
             <div className=" flex justify-end">
                {isAssistant ? (
                  index !== 0 && (
                    <AssistantGroupButton
                      messageId={item.id}
                      content={item.voiceanswer || item.content}
                      prompt={item.prompt}
                      showLikeButton={showLikeButton}
                      audioBinary={item.audio_binary}
                      showLoudspeaker={showLoudspeaker}
                    ></AssistantGroupButton>
                  )
                ) : (
                  <UserGroupButton
                    content={item.content}
                    messageId={item.id}
                    removeMessageById={removeMessageById}
                    regenerateMessage={
                      regenerateMessage && handleRegenerateMessage
                    }
                    sendLoading={sendLoading}
                  ></UserGroupButton>
                )}
              </div>
          </Flex>
        </div>
      </section>
      {visible && (
        <IndentedTreeModal
          visible={visible}
          hideModal={hideModal}
          documentId={clickedDocumentId}
        ></IndentedTreeModal>
      )}
    </div>
  );
};

export default memo(MessageItem);
